﻿using DefeatEpidemic.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace DefeatEpidemic.Base
{
    public class GlobalActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {            
        }

        /// <summary>
        /// Action 执行前拦截[模型验证应该在此处先处理]
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {            
            string isAuth = ConfigurationHelper.GetSectionValue("authorized");
            if (isAuth == "1")
            {
                context.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";//解决拦截器添加后跨域不生效的问题
                var token = context.HttpContext.Request.Headers["token"];
                Response resp = ValidateTokenJwt(token);
                if (resp.code != 1)
                {
                    context.Result = new ContentResult
                    {
                        Content = resp.message,
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "text/html;charset=utf-8"
                    };
                }
            }
            //string path = context.HttpContext.Request.Path.ToUriComponent().ToLower();
            //if (!path.Contains("login") && string.IsNullOrEmpty(context.HttpContext.Session.GetString("UserName")))
            //{
            //    context.Result = new RedirectToActionResult("Login", "Admins", null);
            //}           
        }

        public Response ValidateTokenJwt(string encryptToken)
        {
            Response resp = new Response() { code = 5000, message = "failed" };
            #region 
            string secret = Common.ConfigurationHelper.GetSectionValue("TokenSecret");
            //后续再加上后面的验证
            //解析Token，
            string json = "";
            if (!JwtHelper.DecryptToken(encryptToken, secret, out json))
            {
                resp.code = 5001;
                resp.message = "验签失败";
                return resp;
            }
            //验证载荷信息
            JwtModel jwtModel = new JwtModel();
            if (!JwtHelper.DeserializeJsonToModel(json, out jwtModel))
            {
                resp.code = 5002;
                resp.message = "序列化失败";
                return resp;
            }
            //判断Token的绝对过期时间
            if (JwtHelper.ConvertStringToDateTime(jwtModel.exp) > DateTime.Now)
            {
                resp.code = 1;
                resp.message = "success";
                return resp;
            }
            #endregion

            return resp;
        }
    }
}
